package com.iven.xie.redis.controller;

import com.iven.xie.redis.beans.ResObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * redis的事务用于执行一组命令，中途不被其他的命令所打断
 * 这种一次性发送多个命令，然后等待所有回复的做法称为流水线（pipelining）,它
 * 减少了通信次数可以提高性能
 *
 * @author iven.xie
 */
@Api(tags = "一个jedis提交redis事务的实例接口")
@RestController
@RequestMapping("api/demo")
@Slf4j
public class DemoController {

    @Autowired
    JedisPool pool;

    @ApiOperation("提交事务")
    @PostMapping(value = "/transaction")
    @ResponseBody
    public ResObject transaction() {
        Jedis conn = pool.getResource();
        conn.select(15);
        conn.set("tracn", "5");
        // 开启watch命令，若tracn的值发生变化，则事务提交失败
        String watch = conn.watch("tracn");
        // 开启事务
        Transaction transaction2 = conn.multi();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        transaction2.set("tracn", "100");
        transaction2.set("tracn", "200");
        // 提交事务
        List<Object> list = transaction2.exec();
        log.info(String.valueOf(list.size()));
        log.info(conn.get("tracn"));
        conn.close();

        return ResObject.success();
    }

}
